package com.thenie.web;



import com.google.gson.Gson;
import com.thenie.pojo.Book;
import com.thenie.pojo.Cart;
import com.thenie.pojo.CartItem;
import com.thenie.service.impl.BookServiceImpl;
import com.thenie.utils.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CartServlet extends BaseServlet{
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取所添加的图书编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        //根据图书编号通过bookService.queryBookById查询图书信息（book）
        BookServiceImpl bookService = new BookServiceImpl();
        Book book = bookService.queryBook(id);
        //将所获取的book类型转换成CartItem类型
        CartItem cartItem = WebUtils.copyBookToCartItem(book, new CartItem());
        //将商品添加到购物车cart.add
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            req.getSession().setAttribute("cart", cart);
        }
        cart.add(cartItem);
        req.getSession().setAttribute("cartLastName", book.getName());

        Map<String,Object> map =new HashMap<>();
        map.put("cartLastName",book.getName());
        map.put("totalCount",cart.getTotalCount());

        Gson gson =new Gson();
        String s = gson.toJson(map);

        resp.getWriter().write(s);
    }
    protected void deleteItem(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);

        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart.getMap()!=null) {
            cart.delete(id);
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }
    protected void clearCart(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart.getMap()!=null) {
            cart.clear();
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }

    protected void updateItemCount(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        int count = WebUtils.parseInt(req.getParameter("count"), 0);
        Cart cart = (Cart) req.getSession().getAttribute("cart");

        if(count==0){
            cart.delete(id);
        }else {
            cart.updateCount(id, count);
        }
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
